package org.example.engine;


import com.alipay.remoting.exception.CodecException;
import com.lmax.disruptor.EventHandler;
import io.netty.util.collection.IntObjectHashMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.CommonMsg;
import org.example.MsgConstants;
import org.example.order.CmdType;
import org.example.order.MatchData;
import org.example.order.MatchEvent;
import org.example.service.MQTTClient;
import org.springframework.util.CollectionUtils;

import java.text.Normalizer;
import java.util.List;

@Slf4j
public class L1PubHandler implements EventHandler<RbCmd> {

    private final MQTTClient client;
    private final IntObjectHashMap<List<MatchData>> matcherEventMap;

    public L1PubHandler(MQTTClient client, IntObjectHashMap<List<MatchData>> matcherEventMap) {
        this.client = client;
        this.matcherEventMap = matcherEventMap;
        System.out.println(this.matcherEventMap.keySet().toString());
    }

    @Override
    public void onEvent(RbCmd rbCmd, long l, boolean b) throws Exception {

        final CmdType cmdType = rbCmd.command;
        System.out.println("l1pubevent .................." + matcherEventMap.keySet().toString());
        if(cmdType == CmdType.NEW_ORDER) {
            for(MatchEvent e : rbCmd.matchEventList) {
                System.out.println("event.member.id=" + e.mid);
                matcherEventMap.get(e.mid).add(e.copy());
            }
        }else if (cmdType == CmdType.HQ_PUB) {

            matcherEventMap.values().forEach(list -> {
                list.forEach(matchData -> {
                    try {
                        System.out.println("-----try to publish data");
                        byte[] bytes = matchData.serialize();
                        CommonMsg commonMsg = createCommonMsg(bytes, -1,MsgConstants.MATCH_HQ_DATA);
                        this.client.publish(commonMsg);
                    } catch (CodecException e) {
                        log.error("",e);
                    }
                });
                list.clear();
            });
        }
    }

    private CommonMsg createCommonMsg(byte[] bytes, int i, short matchHqData) {
        CommonMsg msg = new CommonMsg();
        msg.setBodyLength(bytes.length);
        msg.setChecksum(msg.getChecksum());
        msg.setMsgSrc((short)1);
        msg.setMsgDst((short)i);
        msg.setMsgType(matchHqData);
        msg.setStatus(MsgConstants.NORMAL);
        msg.setBody(bytes);
        return msg;
    }

}
